import {
	AnimatedSprite,
	Texture,
	BaseTexture,
	Rectangle,
	LoaderResource,
	Loader
} from "pixi.js";
import GIF from "./utils/gif/Gif";
import Mixin from './utils/Mixin.js';
import DrawBase from './DrawBase.js';

const {
	Uint8Array
} = window;

/**
 * GIF
 *
 * GifItem
 * 
 * @extends PIXI.AnimatedSprite
 * @class
 * @memberof Nice.DrawBase
 * @author iwangcj
 */
class GifItem extends AnimatedSprite {

	constructor(imagepath = "") {
        let frames = [Texture.EMPTY];
		super(frames);

		this.image = imagepath || "";
	}

	_getGifFrames(r) {

		let frames = [],
			gif = new GIF(new Uint8Array(r.data)),
			gifFrames = gif.decompressFrames(true),
			gifWidth = gifFrames[0].dims.width,
			gifHeight = gifFrames[0].dims.height,
			gifCanvas = document.createElement('canvas'),
			gifCtx = gifCanvas.getContext('2d'),
			gifImageData = gifCtx.createImageData(gifWidth, gifHeight);
		gifCanvas.width = gifWidth * gifFrames.length;
        gifCanvas.height = gifHeight;
        
		var gifSpriteSheet = new BaseTexture.from(gifCanvas);
		gifFrames.map(function (f, i) {
			gifImageData.data.set(f.patch);
			gifCtx.putImageData(gifImageData, i * gifWidth, 0);
		}).map(function (f, i) {
			frames.push(new Texture(gifSpriteSheet, new Rectangle(i * gifWidth, 0, gifWidth, gifHeight)));
		});
		return frames;
	}

	_onGifLoad(loader, res) {
        let animatedFrames = [];
        const self = this;
		Object.keys(res).forEach(function (k) {
			res[k].data && animatedFrames.push(self._getGifFrames(res[k]));
		});

		let frames = animatedFrames[Math.round(Math.random() * (animatedFrames.length - 1))];
		this.textures = frames;
		this.scale.set(0.5)
		this.anchor.set(0, 0);
		this.animationSpeed = 0.2;
		this.gotoAndPlay(Math.round(Math.random() * frames.length - 1));

	}

	_loadImage(image) {
        const self = this;
		LoaderResource.setExtensionLoadType('gif', LoaderResource.LOAD_TYPE.XHR);
		LoaderResource.setExtensionXhrType('gif', LoaderResource.XHR_RESPONSE_TYPE.BUFFER);

		const loader = new Loader();
		loader.add([
			image
        ]).load(function(loader, res) {
            self._onGifLoad.apply(self, [loader, res]);
        });

	}

	get image() {
		return this._image;
	}

	set image(image) {
		if (image && typeof image === 'string' && image.indexOf(".gif") != -1) {
			this._image = image;
			this._loadImage(image);
		}
	}

	/**
	 * 获取风格属性
	 * @param {string} key 
	 */
	_getAttrStyle(key) {

        let result = undefined; //未定义
        if ('visible' === key) {
            result = this.visible;
        }

        return result;
    }

	/**
	 * 设置风格属性
	 * @param {string} key 
	 * @param {any} value
	 */
    _setAtterStyle(key, value=undefined) {
        let isOk = true;
        if ('visible' === key) {
            this.visible = value;
        }
        else {
            isOk = false;
        }
        return isOk;
    }


	/**
     * @param {*} key 
     * @param {*} value 
     */
    attrStyle(key, value=undefined) {
        if (undefined != value) {
            return this._setAtterStyle(key, value)
        }
        else {
            return this._getAttrStyle(key);
        }
    }

	/**
     * get/set 属性
     * @param {*} key 
     * @param {*} value 
     */
    attr(key, value) {
        if (undefined != value) {
			let isOk = this.attrBase(key, value);
			!isOk && (isOk = this.attrStyle(key, value));
			return isOk;
        }
        else {
			let result = this.attrBase(key);
			undefined == result && (result = this.attrStyle(key));
            return result;
        }
    }

}

export default Mixin(GifItem, DrawBase);